package org.example.controller;

import lombok.SneakyThrows;
import org.apache.poi.xwpf.usermodel.*;
import org.example.pojo.vo.TableVo;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;


@RestController
@RequestMapping("/api/word-table")
public class WordTableController {

    private static final String templateUrl = "C:\\Users\\SIM\\OneDrive\\EASA翻译\\实训工卡英文版\\template.docx";

    @SneakyThrows
    @PostMapping("/generate")
    public ResponseEntity<String> generateTemplate(@RequestBody TableVo tableVo) {
        InputStream is = Files.newInputStream(Paths.get(templateUrl));
        XWPFDocument document = new XWPFDocument(is);
        System.out.println(document.getTables().size());
        return null;
    }

    @SneakyThrows
    public static void main(String[] args) {
        TableVo tableVo = new TableVo();

        InputStream is = Files.newInputStream(Paths.get(templateUrl));
        XWPFDocument document = new XWPFDocument(is);

        XWPFRun run = getRun(document,0,2,3);
        setFont1(run, tableVo.getWorkCardNumber());

        run = getRun(document,0,4,0);
        setFont1(run, tableVo.getChapterNumber());

        run = getRun(document,0,4,1);
        setFont1(run, tableVo.getReferenceManHours());

        run = getRun(document,0,4,2);
        setFont1(run, tableVo.getMaintenanceInterval());

        run = getRun(document,0,4,3);
        setFont1(run, tableVo.getWorkLocation());

        run = getRun(document,0,4,4);
        setFont1(run, tableVo.getRevision());

        run = getRun(document,0,6,0);
        setFont1(run, tableVo.getPreparedByDate());

        run = getRun(document,0,6,1);
        setFont1(run, tableVo.getReviewedByDate());

        run = getRun(document,0,6,2);
        setFont1(run, tableVo.getApprovedByDate());

        run = getRun(document,0,6,3);
        setFont1(run, tableVo.getActualManHours());

        run = getRun(document,0,6,4);
        setFont1(run, tableVo.getInstructor());

        String wordPath = "C:\\Users\\SIM\\Desktop\\result.docx";
        FileOutputStream outputStream1 = new FileOutputStream(wordPath);
        document.write(outputStream1);
        outputStream1.close();
        document.close();
    }

    private static XWPFRun getRun(XWPFDocument document,int table,int row,int col) {
        XWPFTable table0 = document.getTables().get(table);
        XWPFTableCell cell = table0.getRows().get(row).getCell(col);
        XWPFParagraph paragraph = cell.getParagraphs().get(0);
        XWPFRun run = paragraph.createRun();
        return run;
    }

    private static void setFont1(XWPFRun run,String text) {
        run.setText(text);
        run.setBold(false);
        run.setFontFamily("Arial");
        run.setFontSize(11);
    }
}
